package classify

import (
	"errors"
	classifyDto "news_for_deepseek_interface/dto/admin/classify"
	"news_for_deepseek_interface/model"
	"strconv"
	"time"

	"gorm.io/gorm"
)

func Update(params classifyDto.UpdateRequest) error {

	db := model.GetInstance().GetDB()

	//查询自己
	var classify model.ClassifyModel
	if err := db.Model(&model.ClassifyModel{}).Where("id = ?", params.Id).First(&classify).Error; err != nil {
		return errors.New("分类不存在")
	}

	parentPath := classify.ParentPath

	if classify.ParentId != params.ParentId {
		//查询父级分类
		var parentClassify model.ClassifyModel
		if err := db.Where("parent_id = ?", params.ParentId).First(&parentClassify).Error; err != nil {
			if !errors.Is(err, gorm.ErrRecordNotFound) {
				return errors.New("父级分类不存在")
			}
		}

		parentPath = parentClassify.ParentPath + "," + strconv.Itoa(parentClassify.Id)
	}

	return model.GetInstance().GetDB().
		Model(&model.ClassifyModel{}).
		Where("id = ?", params.Id).
		Debug().
		Updates(map[string]interface{}{
			"title":       params.Title,
			"parent_id":   params.ParentId,
			"parent_path": parentPath,
			"updated_at":  time.Now(),
		}).Error
}
